package az.mecid.rssreader.client;

import az.mecid.rssreader.client.presenter.Presenter;
import az.mecid.rssreader.client.presenter.ReaderPresenter;
import az.mecid.rssreader.client.services.SubscribeServiceAsync;
import az.mecid.rssreader.client.view.ReaderView;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.HasWidgets;

/**
 * Created by IntelliJ IDEA.
 * User: mega
 * Date: 07.03.2010
 * Time: 20:27:02
 */
public class AppController implements Presenter, ValueChangeHandler<String> {

        private HandlerManager eventBus;
        private HasWidgets container;
        private SubscribeServiceAsync feedServiceAsync;

        public AppController(HandlerManager eventBus, SubscribeServiceAsync feedServiceAsync) {
            this.eventBus = eventBus;
            this.feedServiceAsync = feedServiceAsync;
            bind();
        }

        private void bind() {
            History.addValueChangeHandler(this);
        }

        public void go(HasWidgets container) {
            this.container = container;

            if(History.getToken().equals(""))
                History.newItem("overview");
            else
                History.fireCurrentHistoryState();
        }

        public void onValueChange(ValueChangeEvent<String> stringValueChangeEvent) {
            String token = stringValueChangeEvent.getValue();

            if(token != null){
                Presenter presenter = null;

                if(token.equals("overview"))
                    presenter = new ReaderPresenter(new ReaderView(),eventBus,feedServiceAsync);

                if(presenter != null)
                    presenter.go(container);
            }
        }
}